package com.wolfman.wolfchat.controller;

import com.wolfman.wolfchat.annotation.NeedAuthentication;
import com.wolfman.wolfchat.po.User;
import com.wolfman.wolfchat.service.UserService;
import com.wolfman.wolfchat.utils.JwtUtil;
import com.wolfman.wolfchat.vo.Result;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @Title
 * @Description
 * @Author WolfMan
 * @Date 2022/1/14 12:18
 * @Email 2370032534@qq.com
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    UserService userService;

    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return Result.error("用户名或密码不能为空！");
        }
        return userService.register(user);
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())) {
            return Result.error("用户名或密码不能为空！");
        }
        HashMap<String, Object> map = new HashMap<>(2);
        User u = userService.login(user);
        if (u == null) {
            return Result.error("用户名或密码错误！");
        }
        map.put("user", u);
        map.put("token", JwtUtil.generateJwt(u));
        return Result.success(map);
    }

    @NeedAuthentication
    @GetMapping("/selectUserById")
    public Result selectUserById(@RequestParam("userId") Integer userId) {
        if (StringUtils.isEmpty(userId)) {
            return Result.error("用户id不能为空！");
        }
        return Result.success(userService.selectByUserId(userId));
    }

}
